<template>
  <div class="app-container">
    <el-row class="topNum" :gutter="0">
      <el-col :span="6" class="topText topBorder">
        <h4>总设备数</h4>
        <p style="color:#2727FF">{{deviceStatus.total}}台</p>
      </el-col>
      <el-col :span="6" class="topText topBorder">
        <h4>在线</h4>
        <p style="color:#7BAF2A">{{deviceStatus.onlineNum}}台</p>
      </el-col>
      <el-col :span="6" class="topText topBorder">
        <h4>未激活</h4>
        <p style="color:#E1273E">{{deviceStatus.notActiveNum}}台</p>
      </el-col>
      <el-col :span="6" class="topText topBorder">
        <h4>离线</h4>
        <p style="color:#222222">{{deviceStatus.offLineNum}}台</p>
      </el-col>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="充电桩名称" prop="pileName">
        <el-input v-model="queryParams.pileName" placeholder="请输入充电桩名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="场站" prop="stationId">
        <el-select v-model="queryParams.stationId" placeholder="请选择场站" clearable>
          <el-option v-for="station in stationList" :key="station.chargeStationId" :label="station.chargeStationName"
                     :value="station.chargeStationId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="userStatus">
        <el-select v-model="queryParams.deviceState" placeholder="请选择设备状态" clearable>
          <el-option v-for="dict in dict.type.iot_device_state" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['station:pile:add']">新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="pileList">
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="充电桩名称" align="center" prop="pileName"/>
      <el-table-column label="充电桩编号" align="center" prop="deviceId"/>
      <el-table-column label="充电枪数量" align="center" prop="portNum"/>
      <el-table-column label="终端类型" align="center" prop="terminalType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.current_type" :value="scope.row.terminalType"/>
        </template>
      </el-table-column>
      <el-table-column label="出厂日期" align="center" prop="factoryDate"/>
      <el-table-column label="设备厂商" align="center" prop="producer"/>
      <el-table-column label="场站名称" align="center" prop="chargeStationName"/>
      <!-- <el-table-column label="服务状态" align="center" prop="serviceStatus" >
         <template slot-scope="scope">
           <dict-tag :options="dict.type.use_state" :value="scope.row.serviceStatus" />
         </template>
       </el-table-column>-->

      <el-table-column label="设备状态" align="center" prop="deviceState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_device_state" :value="scope.row.deviceState"/>
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center" prop="qr_code">
        <template slot-scope="scope">
          <el-image
            style="width: 25px; height: 25px"
            :src="scope.row.qrCode"
            :preview-src-list="[scope.row.qrCode]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetails(scope.row)"
            v-hasPermi="['custom:pile:info']"
          >详情
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['station:pile:edit']"
          >修改
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['station:pile:del']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getPileList"/>

    <!-- 添加或修改充电桩对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物联设备" prop="deviceId">
          <el-select :disabled="form.$tag === 'edit'" v-model="form.deviceId" placeholder="请选择物联设备" style="width: 100%">
            <el-option
              v-for="item in iotDeviceList"
              :key="item.id"
              :label="item.deviceName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运营商" prop="operatorCode">
          <el-select :disabled="form.$tag === 'edit'" v-model="form.operatorCode" filterable style="width: 340px"
                     placeholder="请选择运营商"
                     @change="getStationAndDeviceList()">
            <el-option
              v-for="item in operatorList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场站" prop="stationId">
          <el-select :disabled="form.$tag === 'edit'" v-model="form.stationId" placeholder="请选择场站" style="width: 100%">
            <el-option
              v-for="item in stationList"
              :key="item.chargeStationId"
              :label="item.chargeStationName"
              :value="item.chargeStationId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充电桩名称" prop="pileName">
          <el-input v-model="form.pileName" placeholder="请输入充电桩名称"/>
        </el-form-item>
        <el-form-item label="出厂日期" prop="factoryDate">
          <el-date-picker style="width: 100%"
            v-model="form.factoryDate"
            type="datetime"
            value-format="yyyy-MM-dd"
            placeholder="请选择出厂日期"/>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch
            v-model="form.status"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="80%" center append-to-body>
      <el-row :gutter="10">
        <el-col :span="13">
          <el-card shadow="never" style="height: 700px; border: hidden">
            <div style="text-align:center;" slot="header">
              <dict-tag style="color: green; font-weight: bold; font-size: 20px" :options="dict.type.use_state"
                        :value="form.serviceStatus"/>
            </div>
            <div style="height: 30%">
              <el-row :gutter="10">
                <el-col :span="8" style="height: auto">
                  <div style="text-align:center;">
                    <el-image style="width: 100px; height: 100px"
                              src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"/>
                    <p>充电桩模型</p>
                  </div>
                </el-col>
                <el-col :span="16">
                  <el-descriptions :labelStyle="{fontWeight: 'bold'}" style="float: right;" direction="vertical"
                                   :column="4">
                    <el-descriptions-item label="充电桩名称">{{form.pileName}}</el-descriptions-item>
                    <el-descriptions-item label="充电桩编号">{{form.deviceId}}</el-descriptions-item>
                    <el-descriptions-item label="充电枪数量">{{form.portNum}}</el-descriptions-item>
                    <el-descriptions-item label="设备厂商">{{form.producer}}</el-descriptions-item>
                    <el-descriptions-item label="出厂日期">{{form.factoryDate}}</el-descriptions-item>
                    <el-descriptions-item label="场站名称">{{form.chargeStationName}}</el-descriptions-item>
                    <el-descriptions-item label="终端类型">
                      <dict-tag :options="dict.type.current_type" :value="form.terminalType"/>
                    </el-descriptions-item>
                    <el-descriptions-item label="额定功率">{{form.ratedPower}}W</el-descriptions-item>
                  </el-descriptions>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
        <el-col :span="11">
          <el-card shadow="never" style="height: 700px; border: hidden">
            <div slot="header">
              <span style="color: darkred; font-weight: bold; font-size: 20px">充电记录</span>
              <el-date-picker
                @blur="onBulr"
                style="float: right;"
                size="mini"
                v-model="dateArray"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :clearable="false">
              </el-date-picker>
            </div>
            <el-table v-loading="loading" :data="orderList" height="600px">
              <el-table-column label="开始时间" align="center" prop="startTime"/>
              <el-table-column label="结束时间" align="center" prop="endTime"/>
              <el-table-column label="电量" align="center" prop="totalPower">
                <template slot-scope="scope">{{scope.row.totalPower}}kw·h</template>
              </el-table-column>
              <el-table-column label="时长" align="center">
                <template slot-scope="scope">{{getChargeTime(scope.row)}}h</template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>

</template>

<script>
  import { queryDevice } from '@/api/iot/device'
  import { listStation } from '@/api/smart/operator/station'
  import { orderList } from '@/api/smart/custom/orderInfo'
  import { getList, add, edit, del, info, getStatus } from '@/api/smart/device/pile'
  import { getOperatorList } from '@/api/smart/operator/electricityPrice'

  export default {
    name: 'pile',
    dicts: ['use_state', 'current_type', 'iot_device_state', 'iot_device_state'],
    data() {
      return {
        // 遮罩层
        loading: true,
        title: '',
        detailTitle: '',
        open: false,
        detailOpen: false,
        stationList: [],
        iotDeviceList: [],
        pileList: [],
        orderList: [],
        //服务商列表
        operatorList: [],
        deviceStatus: {
          total: 0,
          offLineNum: 0,
          notActiveNum: 0,
          onlineNum: 0
        },
        dateArray: [new Date(new Date() - 7 * 24 * 3600 * 1000), new Date()],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          pileName: null,
          stationId: null,
          operatorCode: null,
          serviceStatus: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          deviceId: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }, {
            max: 23,
            message: '最大字符数不能超过23个字符！',
            trigger: 'blur'
          }],
          pileName: [{ required: true, message: '充电桩名称不能为空', trigger: 'blur' }, {
            max: 30,
            message: '最大字符数不能超过30个字符！',
            trigger: 'blur'
          }],
          operatorCode: [{ required: true, message: '运营商不能为空', trigger: 'blur' }],
          stationId: [{ required: true, message: '场站不能为空', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.init()
      this.getStationAndDeviceList()
      this.getOperatorList()
    },
    methods: {
      init() {
        this.getPileList()
        this.getDeviceStatus()
      },
      /*查询运营商列表*/
      getOperatorList() {
        getOperatorList().then(response => {
          this.operatorList = response.data
        })
      },
      //获取设备状态概览
      getDeviceStatus() {
        this.loading = true
        getStatus().then(res => {
          this.deviceStatus = res.data
          this.loading = false
        })
      },
      //获取充电桩列表
      getPileList() {
        this.loading = true
        getList(this.queryParams).then(res => {
          this.pileList = res.rows
          this.total = res.total
          this.loading = false
        })
      },
      //提交按钮
      submitForm() {
        let param = this.form
        const stationCode = this.getStationCode(param.stationId)
        param.stationCode = stationCode
        this.$refs['form'].validate(valid => {
          if (!valid) return
          switch (this.form.$tag) {
            case 'edit':
              edit(param).then(res => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getPileList()
              })
              break
            case 'add':
              add(param).then(res => {
                this.$modal.msgSuccess('添加成功')
                this.open = false
                this.init()
              })
              break
          }
        })
      },
      //详情按钮操作
      handleDetails(row) {
        this.detailOpen = true
        this.form = row
        info(row.deviceId).then(res => {
          this.form = res.data
          this.form.chargeStationName = row.chargeStationName
          this.detailTitle = this.form.pileName + '详情'
        })
        this.getOrderList()
      },
      //新增操作
      handleAdd() {
        this.form = {}
        this.form.$tag = 'add'
        this.title = '添加充电桩'
        this.open = true
      },
      //修改操作
      handleUpdate(row) {
        this.form = Object.assign({}, row)
        this.form.$tag = 'edit'
        this.title = '修改充电桩'
        this.open = true
      },
      //删除操作
      handleDelete(row) {
        const deviceId = row.deviceId
        this.$modal.confirm('是否确认删除充电桩编号为"' + deviceId + '"的数据项？').then(function() {
          return del(deviceId)
        }).then(() => {
          this.init()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      },
      //
      getOrderList() {
        this.loading = true
        orderList({
          deviceId: this.form.deviceId,
          startDate: this.dateArray[0].toLocaleString(),
          endDate: this.dateArray[1].toLocaleString()
        }).then(res => {
          this.orderList = res.data
          this.loading = false
        })
      },
      //计算充电时长
      getChargeTime(row) {
        if (!row.startTime && !row.endTime) {
          return '-'
        }
        let number = new Date(row.endTime).getTime() - new Date(row.startTime).getTime()
        return (number / 60 / 60 / 1000).toFixed(2)
      },
      //
      onBulr() {
        this.getOrderList()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getPileList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.queryParams.serviceStatus = null
        this.handleQuery()
      },
      /** 查询场站和设备列表 */
      async getStationAndDeviceList() {
        this.queryParams.operatorCode = this.form.operatorCode
        this.loading = true
        await listStation(this.queryParams).then(response => {
          this.stationList = response.rows
        })
        await queryDevice().then(res => {
          this.iotDeviceList = res.data
        })
        this.loading = false
      },
      //获取场站编码
      getStationCode(selectedValue) {
        const selectedStation = this.stationList.find(station => station.chargeStationId === selectedValue)
        return selectedStation ? selectedStation.chargeStationCode : ''
      }
    }
  }
</script>

<style lang="scss" scoped>
  .topNum {
    margin: 20px 0;

    h4 {
      font-size: 14px;
      color: #8D8D8D;
      margin: 0 !important;
    }

    p {
      font-size: 23px;
      margin: 10px 0 0 !important;
    }

    .topText {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    .topBorder {
      border-right: 1px solid #F1F1F1;
    }
  }

  .ds-label {
    font-weight: bold;
    color: #ff0000;
  }

</style>
